import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_edit_callback_widget/common_edit_callback_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_list_page_widget/common_list_page_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_pack_up_keyboard_widget/common_pack_up_keyboard_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_title_edit_with_underline_widget/typeof/common_title_edit_with_underline_typeof.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/check_in_statistics/widgets/pages/check_dialog_value_bean.dart';
import 'package:e_reception_flutter/ui/create_user/user_selectsort/bean/department_response_bean.dart';
import 'package:e_reception_flutter/ui/person_detail/bean/person_detail_response_bean.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_string_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_arch_lib.dart';

import '../check_in_statistics_view_model.dart';

class CheckButtonSelectDepartmentWidget extends StatefulWidget {
  final List<MDepartmentListBean> mDepartment;
  final String departmentIds;
  const CheckButtonSelectDepartmentWidget(
      {Key key, this.mDepartment, this.departmentIds})
      : super(key: key);

  @override
  _CheckButtonSelectDepartmentWidgetState createState() =>
      _CheckButtonSelectDepartmentWidgetState();

  ///跳转方法
  static Future<EditTextAndValue> navigatorPush(
      BuildContext context, List<MDepartmentListBean> mDepartment,String departmentIds) {
    return RouterUtils.routeForFutureResult<EditTextAndValue>(
      context,
      CheckButtonSelectDepartmentWidget(
          mDepartment:mDepartment,
          departmentIds:departmentIds
      ),
    );
  }
}

class _CheckButtonSelectDepartmentWidgetState
    extends BaseState<CheckButtonSelectDepartmentWidget> {
  CommonListPageWidgetState<DepartmentListItemBean, DepartmentResponseBean>
  _mState;

  CheckInStatisicsViewModel _viewModel;
  List<MDepartmentListBean> mDepartmentValue;
  String keyword = "";

  void setCommonListState(
      CommonListPageWidgetState<DepartmentListItemBean, DepartmentResponseBean>
      state) {
    _mState = state;
  }
  List<MDepartmentListBean> deprtmentids;
  // List<MDepartmentListBean> deprtmentidsSort;
  @override
  void initState() {
    super.initState();
    deprtmentids = List<MDepartmentListBean>();
    _viewModel = CheckInStatisicsViewModel(this);
    mDepartmentValue = List<MDepartmentListBean>();
    _viewModel?.DCvalueNotifier?.addListener(() {
      // if(_viewModel?.DCvalueNotifier?.value?.length != 0){
        mDepartmentValue = _viewModel?.DCvalueNotifier?.value;
      // }
      // else{
      //   mDepartmentValue = widget?.mDepartment;
      // }

      if(deprtmentids?.length!=0){
        String searchDepartmentIds = deprtmentids?.map((e) => e?.departmentid)?.toString();
        mDepartmentValue?.forEach((element) {
          if(searchDepartmentIds?.contains(element?.departmentid)){
            element?.selected = true;
            // deprtmentids?.add(element);
          }
        });
      }
      if(widget?.departmentIds!=null && widget?.departmentIds!=""){
        mDepartmentValue?.forEach((element) {
          if(widget?.departmentIds?.contains(element?.departmentid?.toString())){
            element?.selected = true;
            if(!(deprtmentids?.map((e) => e?.departmentid)?.toString()?.contains(element?.departmentid))){
              deprtmentids?.add(element);
            }
          }
        });
        _top();
      }
      setState(() { });
    });
    _viewModel?.getSimpleData("00");
    setState(() { });
  }

  void _top(){
    List<MDepartmentListBean> departmentList = List<MDepartmentListBean>();
    mDepartmentValue?.forEach((element) {
      if(widget?.departmentIds?.contains(element?.departmentid?.toString())){
        departmentList?.insert(0, element);
      }else{
        departmentList?.add(element);
      }
    });
    mDepartmentValue = departmentList;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // resizeToAvoidBottomInset: false,
      // resizeToAvoidBottomPadding: false,
      backgroundColor: Color(0xFF191E31),
      body: CommonPackUpKeyboardWidget(
        child: Column(
          mainAxisSize: MainAxisSize.max,
          children: <Widget>[
            _toTopBarWidget(),
            _searchDepartmentWidget(),
            SizedBox(
              height: 10,
            ),
            Expanded(child: _toCustomListWidget()),
            _toHorizontalBar()
          ],
        ),
      ),
    );
  }


  Widget _toTopBarWidget() {
    return VgTopBarWidget(
      title: "选择部门",
      // rightWidget: _buttonWidget(),
    );
  }

  Widget _buttonWidget() {
    return Container(
      child: CommonFixedHeightConfirmButtonWidget(
        isAlive: true,
        width: 90,
        height: 36,
        unSelectBgColor:
        ThemeRepository.getInstance().getTextEditHintColor_3A3F50(),
        selectedBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
        unSelectTextStyle: TextStyle(
            color: ((deprtmentids?.length??0) != 0)?VgColors.INPUT_BG_COLOR :VgColors.INPUT_BG_COLOR.withOpacity(0.5),
            fontSize: 15,
            fontWeight: FontWeight.w600),
        selectedTextStyle: TextStyle(
            color:((deprtmentids?.length??0) != 0) ?ThemeRepository.getInstance().getTextMainColor_D0E0F7() : ThemeRepository.getInstance().getTextMainColor_D0E0F7().withOpacity(0.5), fontSize: 15, fontWeight: FontWeight.w600),
        text: "确定",
        onTap: () {
          //提交按钮
          if (deprtmentids?.length != 0 && deprtmentids != null) {
            _httpSave();
          }
        },
      ),
    );
  }

  Widget _toHorizontalBar(){
    return Container(
      height: 56,
      color: Color(0xFF3A3F50),
      // margin: const EdgeInsets.symmetric(horizontal: 15),
      child: Row(
        mainAxisSize: MainAxisSize.max,
        children: <Widget>[
          SizedBox(width: 15,),
          GestureDetector(
            onTap: (){
              if(mDepartmentValue==null){
                return;
              }
              if(mDepartmentValue?.length != deprtmentids?.length){
                mDepartmentValue?.forEach((element) {
                  if(!(element?.selected ?? false)){
                    element?.selected = true;
                    deprtmentids.add(element);
                  }
                });
              }else{
                mDepartmentValue?.forEach((element) {
                    element?.selected = false;
                    deprtmentids.remove(element);
                });
              }
              setState(() { });
            },
            child: Text(
                ((deprtmentids?.length??0) == (mDepartmentValue?.length??0) && (deprtmentids?.length??0)!=0)?"全不选" :"全选",
                style: TextStyle(color: Color(0xFFD0E0F7), fontSize: 15)),
          ),
          SizedBox(width: 15,),

          Text(((deprtmentids?.length??0) != 0) ?"已选${deprtmentids?.length ?? 0}部门" :"",
              style: TextStyle(color: Color(0xFF1890FF), fontSize: 12)),
          Spacer(),
          _buttonWidget(),
          SizedBox(width: 15,),
        ],
      ),
    );
  }

  Widget _defaultEmptyCustomWidget() {
    return Padding(
      padding: const EdgeInsets.only(top: 120),
      child: Column(
        mainAxisSize: MainAxisSize.max,
        children: <Widget>[
          Image.asset("images/empty_icon.png",width: 120,gaplessPlayback: true,),
          Text(
            "暂无内容",
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              color: VgColors.INPUT_BG_COLOR,
              fontSize: 13,
            ),
          )
        ],
      ),
    );
  }

  //封装的列表
  Widget _toCustomListWidget() {
    // if((mDepartmentValue?.length ?? 0)==0){
    //   return _defaultEmptyCustomWidget();
    // }
    return VgPlaceHolderStatusWidget(
      loadingStatus:keyword=="" ? (mDepartmentValue?.length??0) == 0 : false,
      emptyStatus: keyword!=""&&(mDepartmentValue?.length??0) == 0,
      // errorCustomWidget: _defaultEmptyCustomWidget(),
      //   emptyCustomWidget:_defaultEmptyCustomWidget(),
      child: ListView.separated(
          itemCount: mDepartmentValue?.length ?? 0,
          padding: const EdgeInsets.all(0),
          physics: BouncingScrollPhysics(),
          keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
          itemBuilder: (BuildContext context, int index) {
            return _toListItemWidget(mDepartmentValue?.elementAt(index));
          },
          separatorBuilder: (BuildContext context, int index) {
            return Container(
              height: 0.5,
              color: ThemeRepository.getInstance().getCardBgColor_21263C(),
              padding: const EdgeInsets.only(left: 15),
              child: Container(
                color: Color(0xFF303546),
              ),
            );}
      ),
    );
  }

  Widget _toListItemWidget(MDepartmentListBean itemBean) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () async {
        //判断字体是否选中
        itemBean?.selected = !(itemBean?.selected ?? false);
        if(itemBean?.selected ?? false){
          deprtmentids.add(itemBean);
        }else{
          MDepartmentListBean mbean = MDepartmentListBean();
          deprtmentids?.forEach((element) {
            if(element?.departmentid == itemBean?.departmentid){
              mbean = element;
            }
          });
          deprtmentids.remove(mbean);
        }
        setState(() {});
        VgToolUtils.removeAllFocus(context);
      },
      child: Container(
        color: Color(0xFF21263C),
        height: 50,
        alignment: Alignment.centerLeft,
        padding: const EdgeInsets.symmetric(horizontal: 15),
        child: Row(
          children: [
            Image(
              image: itemBean?.selected ??false
                  ? AssetImage("images/common_selected_ico.png")
                  : AssetImage("images/common_unselect_ico.png"),
              width: 20,
            ),
            SizedBox(width: 8,),
            Container(
              width: (VgToolUtils.getScreenWidth()/3)*2,
              child: Text(
                itemBean?.department ?? "",
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  color: Color(0xFFD0E0F7),
                  fontSize: 14,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _searchDepartmentWidget() {
    return Container(
      height: 30,
      color: Color(0xFF3A3F50),
      child: CommonEditCallbackWidget(
        contentPadding: EdgeInsets.only(top: 0, bottom: 15),
        hintText: "搜索",
        customIcon: "images/common_search_ico.png",
        iconColor: Colors.white54,
        onChanged: (String dText) {
          keyword = dText;
          _viewModel?.getSimpleData("00",keyword: dText);
        },
      ),
    );
  }

  void _httpSave() {
    List<MDepartmentListBean> departmentList = deprtmentids;
    List<String> departmentId = List<String>();
    List<String> departmentName = List<String>();
    for (MDepartmentListBean item in departmentList) {
      departmentId.add(item?.departmentid);
      departmentName?.add(item?.department);
    }
    _pop(departmentId,departmentName);
  }

  ///返回部门选中值
  void _pop(List<String> departmentId,List<String> departmentName) {
    if (departmentId == null) {
      return;
    }
    RouterUtils.pop(context,
        result: EditTextAndValue(value: VgStringUtils.getSplitStr(departmentId,symbol: ","), editText:  VgStringUtils.getSplitStr(departmentName,symbol: ",")));
  }
}
